package com.hmj.excel.frame;

import com.alibaba.fastjson.JSONObject;
import com.hmj.excel.biz.ExcelPrase;
import com.hmj.excel.biz.FinanceService;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TaxActionListener implements ActionListener{
    private JTextField srcField;
    private JTextField dstField;
    private JTextField expressionField;
    public TaxActionListener(JTextField srcField,JTextField dstField,JTextField expressionField){
        this.srcField = srcField;
        this.dstField = dstField;
        this.expressionField = expressionField;
    }
    public void actionPerformed(ActionEvent e) {
        String srcFileName = srcField.getText();
        String dstFileDir = dstField.getText();
        String expression = expressionField.getText();
        if(StringUtils.isEmpty(srcFileName)||
                StringUtils.isEmpty(dstFileDir)||
                StringUtils.isEmpty(expression)){
            JOptionPane.showMessageDialog(null, "Error", "参数不能为空",JOptionPane.WARNING_MESSAGE);
            return;
        }
        File inputFile = new File(srcFileName);
        if(!inputFile.exists()){
            JOptionPane.showMessageDialog(null, "Error", "输入文件不存在",JOptionPane.WARNING_MESSAGE);
            return;
        }
        File dirFile = new File(dstFileDir);

        if(!dirFile.exists()){
            JOptionPane.showMessageDialog(null, "Error", "输出文件目录不存在",JOptionPane.WARNING_MESSAGE);
            return;
        }
        System.out.println(inputFile.getName());
        File outFile = new File(dirFile, "xp_"+inputFile.getName());
        if(!outFile.exists()){
            try {
                outFile.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
                JOptionPane.showMessageDialog(null, "Error", e1.getMessage(),JOptionPane.WARNING_MESSAGE);
                return;
            }
        }
        try {
            Map title = new HashMap();
            List<JSONObject> dataList = ExcelPrase.readExcelFile(inputFile, title);
            FinanceService.expressAndTax(expression,dataList,title);
            OutputStream out = new FileOutputStream(outFile);
            ExcelPrase.exportExcelFile(out,dataList,title);
            out.close();
        } catch (IOException e1) {
            e1.printStackTrace();
            JOptionPane.showMessageDialog(null, "Error", e1.getMessage(),JOptionPane.WARNING_MESSAGE);
        }
        JOptionPane.showMessageDialog(null, "Success", "处理完成",JOptionPane.WARNING_MESSAGE);
    }
}
